<template>
  <el-dialog v-model="showVisible" :title="typeName + '图书类型'" width="600px" destroy-on-close center>
    <el-form status-icon inline ref="formRef" :model="formData" :rules="formRules" label-width="120"
      label-position="right">
      <el-form-item class="w-90s" prop="category_name" label="图书类型名称">
        <el-input type="text" v-model="formData.category_name"  @keyup.enter.native="submitFun" placeholder="图书类型名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFun">
          {{ typeName }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, toRefs } from 'vue';
import { AddCategoryApi, updateCategoryApi } from '@/api/category';
const emit = defineEmits(['on-reset'])
const DEFAULT_FORM = {
  category_name: '',
}
const id = ref()
const formRef = ref();
const formData = ref<any>({ ...DEFAULT_FORM });
const showVisible = ref<boolean>(false);
const actionState = reactive<any>({
  type: 1, // 1 添加 2 修改
  typeName: '添加'
});
const formRules = reactive({
  category_name: [
    { required: true, message: '请填写图书分类名称', trigger: 'blur' },
  ]
});
const { type, typeName } = toRefs(actionState);
// 显示编辑用户框
const showForm = (data?: any): void => {
  type.value = 1;
  typeName.value = '添加';
  formData.value = { ...DEFAULT_FORM }
  if (data) {
    id.value = data.id
    type.value = 2;
    typeName.value = '编辑';
    Object.keys(data).forEach((key: string) => {
      formData.value[key] = data[key];
    });
  }
  showVisible.value = true;
};
// 提交保存
const submitFun = async (): Promise<any> => {
  await formRef.value.validate((val: boolean) => {
    if (val) {
      if (type.value === 1) {
        AddCategoryApi(formData.value).then((_res: any) => {
          showVisible.value = false
          emit('on-reset')
        })
      } else {
        updateCategoryApi(id.value, formData.value).then((_res: any) => {
          showVisible.value = false
          emit('on-reset')
        })
      }
    } else {
      return false;
    }
  })
}
defineExpose({
  showForm
});
</script>
<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;

  .el-button {
    margin: 0 20px;
    width: 120px;
  }
}

.w-90s {
  width: 90%;
}
</style>
